﻿using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;

namespace AutoAllocService.Services.Models
{
    public class AllocTaskStore
    {
        private const string KeyPrefix = "AllocTaskStore";

        public List<string> AllocedDrivers { get; set; }

        public string BookingID { get; }

        public int AllocTimes { get; set; } = 0;

        public string LastStatus { get; set; }

        public string LatestDriver { get; set; }

        public DateTime LatestRunAt { get; set; }

        public AllocTaskStore(string bookingID)
        {
            BookingID = bookingID;
        }

        public static AllocTaskStore Init(string bookingID)
        {
            var key = $"{KeyPrefix}:{bookingID}";
            if (RedisHelper.Instance.KeyExists(key))
            {
                var json = RedisHelper.Instance.StringGet(key);
                return JsonConvert.DeserializeObject<AllocTaskStore>(json);
            }
            else
            {
                return new AllocTaskStore(bookingID)
                {
                    AllocedDrivers = new List<string>()
                };
            }
        }

        public static List<string> GetAllUsingDriver()
        {
            var drivers = RedisHelper.Instance.HashGet<List<string>>("allocTask", "using_drivers");
            if (drivers == null)
                drivers = new List<string>();
            return drivers;
        }

        public static void RemoveUsingDriver(string code)
        {
            var drivers = GetAllUsingDriver();
            drivers.Remove(code);
            RedisHelper.Instance.HashSet("allocTask", "using_drivers", drivers);
        }

        public static void AddUsingDriver(string code)
        {
            var drivers = GetAllUsingDriver();
            drivers.Add(code);
            RedisHelper.Instance.HashSet("allocTask", "using_drivers", drivers);
        }

        public void Save()
        {
            var key = $"{KeyPrefix}:{BookingID}";
            RedisHelper.Instance.StringSet(key, JsonConvert.SerializeObject(this), expiry: TimeSpan.FromHours(1));
        }
    }
}
